<template>
	<div class="cc-table-modify">
		<cc-bar-modify
			:disabled-left="canNotDelete"
			@right-click="addClickHandle"
			@left-click="deleteClickHandler(selectedItems)"
		>
			<template>
				<slot name="title">
					<h3>{{title}}</h3>
				</slot>
			</template>
		</cc-bar-modify>

		<el-table
			ref="tableRef"
			:data="items"
			tooltip-effect="dark"
			style="width: 100%"
			:max-height="maxTableHeight"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="60" />
			<slot></slot>
			<slot name="operate"></slot>
			<slot name="delete">
				<el-table-column width="60">
					<template v-slot="scope">
						<el-tooltip class="item" effect="dark" content="删除" placement="top">
							<el-button
								type="danger"
								icon="el-icon-delete"
								size="mini"
								@click="deleteClickHandler([scope.row])"
								v-if="withDelete"
							/>
						</el-tooltip>
					</template>
				</el-table-column>
			</slot>
		</el-table>
	</div>
</template>

<script>
	import ccBarModify from "../cc-bar-modify";

	export default {
		name: "cc-table-modify",
		components: {
			"cc-bar-modify": ccBarModify
		},
		props: {
			items: {
				type: Array,
				default: () => []
			},
			title: {
				type: String,
				default: "标题"
			},
			withDelete: {
				type: Boolean,
				default: false
			},
			hideConfirm: {
				type: Boolean,
				default: false
			},
			hideConfirmMultiple: {
				type: Boolean,
				default: false
			},
			defaultItem: {
				type: Object,
				default: () => ({})
			},
			maxTableHeight: {
				type: Number
			}
		},
		data() {
			return {
				selectedItems: []
			};
		},
		computed: {
			canNotDelete() {
				return this.selectedItems.length < 1;
			}
		},
		methods: {
			handleSelectionChange(value) {
				this.selectedItems = value;
			},
			async deleteClickHandler(dItems) {
				let res;
				try {
					const showConfirm =
						dItems.length > 1
							? this.hideConfirmMultiple
							: this.hideConfirm;
					res =
						showConfirm ||
						(await this.$confirm("是否确认删除？", "提示", {
							type: "warning"
						})) === "confirm";
				} catch {
					res = false;
				} finally {
					if (res) {
						const rest = this.items.filter(i => !dItems.includes(i));
						this.$emit("change", rest, dItems);
					} else {
						this.$message({
							type: "info",
							message: "操作已取消"
						});
					}
				}
			},
			addClickHandle() {
				if (this._events.add) {
					this.$emit("add");
				} else {
					if (this.items.length && this.items[0] === this.defaultItem)
						return;
					const [...items] = this.items;
					const newItem = Object.assign({}, this.defaultItem);
					items.unshift(newItem);
					this.$emit("change", items, [newItem]);
				}
			}
		}
	};
</script>

<style lang="less" scoped>
</style>
